package com.baixiaowen.xiaoaointerview.大厂笔试_白板面试篇.中文乱码处理;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * @author Baixiaowen
 */
public class WordCount1 {

    public static void main(String[] args) {
        test_chinese();
    }

    public static void test_chinese() {
        String raw = "长坂桥头杀气生，横抢立马眼圆睁。一声好似轰雷震，独退曹家百万兵。";
        Charset charset = StandardCharsets.UTF_8;
        byte[] bytes = charset.encode(raw).array();
        byte[] bytes2 = Arrays.copyOfRange(bytes, 0, 11);

        ByteBuffer bbuf = ByteBuffer.allocate(12);
        CharBuffer cbuf = CharBuffer.allocate(12);

        bbuf.put(bytes2);
        bbuf.flip();

        charset.newDecoder().decode(bbuf, cbuf, true);

        cbuf.flip();

        char[] tmp = new char[cbuf.length()];
        if (cbuf.hasRemaining()) {
            cbuf.get(tmp);
            System.err.println("here:" + new String(tmp));
        }

        System.err.format("limit-pos=%d\n", bbuf.limit() - bbuf.position());

        // 取出UTF-8不能解析的字节，然后将它重新放入到缓冲区 buff中，循环进入到下次读取解析操作中，这样就可以解决中文乱码处理了
        Arrays.copyOfRange(bbuf.array(), bbuf.position(), bbuf.limit());
    }

}
